
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="GO语言之flag的使用">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>GO语言之flag的使用 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        GO语言之flag的使用
      </h1>
      <span>
        
        <time class="time" datetime="2019-10-29T16:00:00.000Z">
        2019-10-30
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>Go语言内置的<code>flag</code>包实现了命令行参数的解析，<code>flag</code>包使得开发命令行工具更为简单。</p>
<p>首先，如果你只是简单的想要获取命令行参数，可以像下面的代码示例一样使用<code>os.Args</code>来获取命令行参数。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">	<span class="string">"os"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">//os.Args demo</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">//os.Args是一个[]string</span></span><br><span class="line">	<span class="keyword">if</span> <span class="built_in">len</span>(os.Args) &gt; <span class="number">0</span> &#123;</span><br><span class="line">		<span class="keyword">for</span> index, arg := <span class="keyword">range</span> os.Args &#123;</span><br><span class="line">			fmt.Printf(<span class="string">"args[%d]=%v\n"</span>, index, arg)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将上面的代码执行<code>go build -o &quot;args_demo&quot;</code>编译之后，执行：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$ ./args_demo a b c d</span><br><span class="line">args[<span class="number">0</span>]=./args_demo</span><br><span class="line">args[<span class="number">1</span>]=a</span><br><span class="line">args[<span class="number">2</span>]=b</span><br><span class="line">args[<span class="number">3</span>]=c</span><br><span class="line">args[<span class="number">4</span>]=d</span><br></pre></td></tr></table></figure>

<p><code>os.Args</code>是一个存储命令行参数的字符串切片，它的第一个元素是执行文件的名称。</p>
<p>但是os内置的这个Args函数，使用方法比较简单，无法满足我们实际工作的需要，因此，我们需要引入一个新的包，<code>flag</code></p>
<h3 id="Flag的使用"><a href="#Flag的使用" class="headerlink" title="Flag的使用"></a>Flag的使用</h3><p>1.导入flag包</p>
<blockquote>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">import</span> flag</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
<p>2.定义命令行flag参数</p>
<p>有以下两种常用的定义命令行<code>flag</code>参数的方法。</p>
<h5 id="flag-Type"><a href="#flag-Type" class="headerlink" title="flag.Type()"></a><code>flag.Type()</code></h5><p>基本格式如下：</p>
<p><code>flag.Type(flag名, 默认值, 帮助信息)*Type</code> 例如我们要定义姓名、年龄、婚否三个命令行参数，我们可以按如下方式定义：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">name := flag.String(<span class="string">"name"</span>, <span class="string">"张三"</span>, <span class="string">"姓名"</span>)</span><br><span class="line">age := flag.Int(<span class="string">"age"</span>, <span class="number">18</span>, <span class="string">"年龄"</span>)</span><br><span class="line">married := flag.Bool(<span class="string">"married"</span>, <span class="literal">false</span>, <span class="string">"婚否"</span>)</span><br><span class="line">delay := flag.Duration(<span class="string">"d"</span>, <span class="number">0</span>, <span class="string">"时间间隔"</span>)</span><br></pre></td></tr></table></figure>

<p>需要注意的是，此时<code>name</code>、<code>age</code>、<code>married</code>、<code>delay</code>均为对应类型的指针。</p>
<h5 id="flag-TypeVar"><a href="#flag-TypeVar" class="headerlink" title="flag.TypeVar()"></a>flag.TypeVar()</h5><p>基本格式如下： <code>flag.TypeVar(Type指针, flag名, 默认值, 帮助信息)</code> 例如我们要定义姓名、年龄、婚否三个命令行参数，我们可以按如下方式定义：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">var</span> name <span class="keyword">string</span></span><br><span class="line"><span class="keyword">var</span> age <span class="keyword">int</span></span><br><span class="line"><span class="keyword">var</span> married <span class="keyword">bool</span></span><br><span class="line"><span class="keyword">var</span> delay time.Duration</span><br><span class="line">flag.StringVar(&amp;name, <span class="string">"name"</span>, <span class="string">"张三"</span>, <span class="string">"姓名"</span>)</span><br><span class="line">flag.IntVar(&amp;age, <span class="string">"age"</span>, <span class="number">18</span>, <span class="string">"年龄"</span>)</span><br><span class="line">flag.BoolVar(&amp;married, <span class="string">"married"</span>, <span class="literal">false</span>, <span class="string">"婚否"</span>)</span><br><span class="line">flag.DurationVar(&amp;delay, <span class="string">"d"</span>, <span class="number">0</span>, <span class="string">"时间间隔"</span>)</span><br></pre></td></tr></table></figure>

<p>3.flag.Parse() 进行解析</p>
<p>通过以上两种方法定义好命令行flag参数后，需要通过调用<code>flag.Parse()</code>来对命令行参数进行解析。</p>
<p>支持的命令行参数格式有以下几种：</p>
<ul>
<li><code>-flag xxx</code> （使用空格，一个<code>-</code>符号）</li>
<li><code>--flag xxx</code> （使用空格，两个<code>-</code>符号）</li>
<li><code>-flag=xxx</code> （使用等号，一个<code>-</code>符号）</li>
<li><code>--flag=xxx</code> （使用等号，两个<code>-</code>符号）</li>
</ul>
<p>其中，布尔类型的参数必须使用等号的方式指定。</p>
<p>Flag解析在第一个非flag参数（单个”-“不是flag参数）之前停止，或者在终止符”–“之后停止。</p>
<p>4.flag的其他函数</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">flag.Args()  <span class="comment">////返回命令行参数后的其他参数，以[]string类型</span></span><br><span class="line">flag.NArg()  <span class="comment">//返回命令行参数后的其他参数个数</span></span><br><span class="line">flag.NFlag() <span class="comment">//返回使用的命令行参数个数</span></span><br></pre></td></tr></table></figure>

<p>5.flag的完整示例</p>
<p>定义：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">//定义命令行参数方式1</span></span><br><span class="line">	<span class="keyword">var</span> name <span class="keyword">string</span></span><br><span class="line">	<span class="keyword">var</span> age <span class="keyword">int</span></span><br><span class="line">	<span class="keyword">var</span> married <span class="keyword">bool</span></span><br><span class="line">	<span class="keyword">var</span> delay time.Duration</span><br><span class="line">	flag.StringVar(&amp;name, <span class="string">"name"</span>, <span class="string">"张三"</span>, <span class="string">"姓名"</span>)</span><br><span class="line">	flag.IntVar(&amp;age, <span class="string">"age"</span>, <span class="number">18</span>, <span class="string">"年龄"</span>)</span><br><span class="line">	flag.BoolVar(&amp;married, <span class="string">"married"</span>, <span class="literal">false</span>, <span class="string">"婚否"</span>)</span><br><span class="line">	flag.DurationVar(&amp;delay, <span class="string">"d"</span>, <span class="number">0</span>, <span class="string">"延迟的时间间隔"</span>)</span><br><span class="line"></span><br><span class="line">	<span class="comment">//解析命令行参数</span></span><br><span class="line">	flag.Parse()</span><br><span class="line">	fmt.Println(name, age, married, delay)</span><br><span class="line">	<span class="comment">//返回命令行参数后的其他参数</span></span><br><span class="line">	fmt.Println(flag.Args())</span><br><span class="line">	<span class="comment">//返回命令行参数后的其他参数个数</span></span><br><span class="line">	fmt.Println(flag.NArg())</span><br><span class="line">	<span class="comment">//返回使用的命令行参数个数</span></span><br><span class="line">	fmt.Println(flag.NFlag())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>命令行参数使用提示：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">$ ./flag_demo -<span class="built_in">help</span></span><br><span class="line">Usage of ./flag_demo:</span><br><span class="line">  -age int</span><br><span class="line">        年龄 (default 18)</span><br><span class="line">  -d duration</span><br><span class="line">        时间间隔</span><br><span class="line">  -married</span><br><span class="line">        婚否</span><br><span class="line">  -name string</span><br><span class="line">        姓名 (default <span class="string">"张三"</span>)</span><br></pre></td></tr></table></figure>

<p>正常使用命令行flag参数：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ ./flag_demo -name szk --age 28 -married=<span class="literal">false</span> -d=1h30m</span><br><span class="line">szk 28 <span class="literal">false</span> 1h30m0s</span><br><span class="line">[]</span><br><span class="line">0</span><br><span class="line">4</span><br></pre></td></tr></table></figure>

<p>使用非flag命令行参数：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ ./flag_demo a b c</span><br><span class="line">张三 18 <span class="literal">false</span> 0s</span><br><span class="line">[a b c]</span><br><span class="line">3</span><br><span class="line">0</span><br></pre></td></tr></table></figure>


    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Flag的使用"><span class="toc-text">Flag的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#flag-Type"><span class="toc-text">flag.Type()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#flag-TypeVar"><span class="toc-text">flag.TypeVar()</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/10/29/Go语言之fmt的使用/" rel="next" title="Go语言之fmt的使用">
          Go语言之fmt的使用
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/11/09/Django的cookie和session介绍/" rel="prev" title="第二十三章 Django cookie 与 session">
            第二十三章 Django cookie 与 session
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
